/*
 * @author zzr
 * @date: 2025/05/07  15:41
 * @description: 模拟实现一个阻塞队列 put 和 take 方法
 */
class MyBlockingQueue {

    private String[] elems = null;
    private int head; // 头引用
    private int tail; // 尾引用
    private int size; // size 用来记录填入队列中的元素个数 ==》 实现循环队列，用 size 判满

    Object locker = new Object();

    public MyBlockingQueue(int capacity) {
        elems = new String[capacity];
    }

    public void put(String elem) throws InterruptedException {

        synchronized (locker) {
            while (size >= elems.length) {
                // 队列满了
                // 实现阻塞逻辑
                locker.wait();
            }
            elems[tail] = elem;
            tail++;
            size++;
            if (tail >= elems.length) {
                tail = 0;
            }
            locker.notify();
        }
    }

    public String take() throws InterruptedException {

        String elem = null;
        synchronized (locker) {
            while (0 == size) {
                // 队列空了
                // 阻塞等待
                locker.wait();
            }
            elem = new String(elems[head]);
            head++;
            size--;
            if (head >= elems.length) {
                head = 0;
            }
            locker.notify();
        }
        return elem;
    }
}

public class Demo4 {
    public static void main(String[] args) {

        MyBlockingQueue myBlockingQueue = new MyBlockingQueue(1000);

        Thread t1 = new Thread(() -> {
            int n = 1;
            while (true) {
                try {
                    myBlockingQueue.put(n + "");
                    System.out.println("生产元素" + n);
                    n++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        });

        Thread t2 = new Thread(() -> {
            while (true) {
                String ret = null;
                try {
                    ret = myBlockingQueue.take();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("消耗元素" + ret);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }
}
